
//
//  RootViewController.m
//  NewProject
//
//  Created by 学鸿 张 on 13-11-29.
//  Copyright (c) 2013年 Steven. All rights reserved.
//

#import "RootViewController.h"
#import "maskLayer.h"
@interface RootViewController ()
@property(nonatomic)BOOL lightOn;
@property(nonatomic, strong)CALayer *maskLayer;
@end

@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _lightOn = NO;
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(shadowImage)])
    {
        [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    }
    
    
    self.navigationController.navigationBarHidden = NO;
    self.title = @"二维码扫描";
   
    
    
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(kWidthOfPt(190), kHeightOfPt(600), kWidthOfPt(700), kHeightOfPt(700))];
    imageView.image = [UIImage imageNamed:@"pick_bg.png"];
    [self.view addSubview:imageView];
    
    UILabel * labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(0, kHeightOfPt(1320), kScreenWidth, 50)];
    labIntroudction.font = systemFontOfPX(36);
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.textColor=[UIColor greenColor];
    labIntroudction.text=@"将二维码放入框内，即可自动扫描";
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:labIntroudction];
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(kWidthOfPt(190), kHeightOfPt(600), kWidthOfPt(700), 2)];
    _line.image = [UIImage imageNamed:@"scanline.png"];
    [self.view addSubview:_line];
    
    CAKeyframeAnimation *keyframeAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(self.view.center.x, kHeightOfPt(600))];
    [path addLineToPoint:CGPointMake(self.view.center.x, kHeightOfPt(700) + kHeightOfPt(600))];
    keyframeAnimation.path = path.CGPath;
    keyframeAnimation.duration = 3.0f;
    keyframeAnimation.repeatCount = HUGE_VALF;
    keyframeAnimation.autoreverses = YES;
    keyframeAnimation.fillMode = kCAFillModeForwards;
    [_line.layer addAnimation:keyframeAnimation forKey:nil];
    
    UIImageView *lightImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kWidthOfPt(160), kHeightOfPt(160))];
    lightImage.center = CGPointMake(self.view.center.x, kHeightOfPt(1530));
    lightImage.image = [UIImage imageNamed:@"noLight.png"];
    lightImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *lightTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openLight:)];
    [lightImage addGestureRecognizer:lightTap];
    [self.view addSubview:lightImage];
    [self addMaskLayer];
}

- (void)openLight:(UITapGestureRecognizer *)tap
{
    UIImageView *iv = (UIImageView *)tap.view;
    _lightOn = !_lightOn;
    if (_lightOn) {
        iv.image = [UIImage imageNamed:@"lighted.png"];
        [self turnOnLed];
    }else{
        iv.image = [UIImage imageNamed:@"noLight.png"];
        [self turnOffLed];
    }


}

-(void)turnOffLed {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}

-(void)turnOnLed {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchModeOn];
        [device unlockForConfiguration];
    }   
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupCamera];
}
- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.bounds;
    _output.rectOfInterest = CGRectMake(kHeightOfPt(600)/kScreenHeight, kWidthOfPt(190)/kScreenWidth, kHeightOfPt(700)/kScreenHeight,kWidthOfPt(700)/kScreenWidth);
    NSLog(@"rect is %@",NSStringFromCGRect(_output.rectOfInterest));
    [self.view.layer insertSublayer:self.preview atIndex:0];
    [_session startRunning];
}

- (void)addMaskLayer
{
    CALayer *layer = [CALayer layer];
    layer.frame = self.view.bounds;
    layer.backgroundColor = [UIColor colorWithHexString:@"000000" alpha:0.5].CGColor;
    [self.view.layer insertSublayer:layer atIndex:1];
    maskLayer *masklayer = [maskLayer layer];
    self.maskLayer = layer;
    masklayer.backgroundColor = [UIColor clearColor].CGColor;
    masklayer.frame = self.view.bounds;
    [masklayer setNeedsDisplay];
    layer.mask = masklayer;
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
   
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        if (self.planteBlock) {
            self.planteBlock(stringValue);
        }
    }
    
    [_session stopRunning];
    [self.navigationController popViewControllerAnimated:YES];
    [_line.layer removeAllAnimations];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
